package org.pt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pt.components.Response;
import org.pt.dto.UserAdminDto;
import org.pt.exception.*;
import org.pt.mapper.CheatAnalysisResultMapper;
import org.pt.mapper.UserMapper;
import org.pt.mapper.WorkMapper;
import org.pt.model.CheatAnalysisResult;
import org.pt.model.User;
import org.pt.model.Work;
import org.pt.utils.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class AdminServiceImpl {

    @Value("${python.service.url}")
    private String pythonServiceUrl;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkMapper workMapper;


    @Autowired
    private CheatAnalysisResultMapper cheatAnalysisResultMapper; // 用于操作 CheatAnalysisResult 表

    public Response<String> bootCheatAnalysis(String token) throws UserException, CheatAnalysisException {
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("验证码无效");
        }

        RestTemplate restTemplate = new RestTemplate();
        String flaskUrl = pythonServiceUrl + "/cheat/data"; // 替换为实际Flask地址

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        try {
            // 3. 发送GET请求到Flask服务
            ResponseEntity<Map> response = restTemplate.exchange(
                    flaskUrl,
                    HttpMethod.GET,
                    requestEntity,
                    Map.class
            );

            // 4. 处理成功响应
            if (response.getStatusCode() == HttpStatus.OK) {
                Map<String, Object> responseBody = response.getBody();
                if ("success".equals(responseBody.get("status"))) {
                    return Response.success("作弊检测分析成功完成");
                } else {
                    throw new CheatAnalysisException("检测系统错误");
                }
            } else {
                throw new CheatAnalysisException("检测系统错误");
            }

        } catch (Exception e) {
            throw new CheatAnalysisException("检测系统其他错误");
        }

    }

    public Response<List<UserAdminDto>> getUserAdminList(String token, int page, int size) throws UserException, CheatAnalysisException {
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("验证码无效");
        }

        // Step 1: 查询所有用户
        List<User> userList = userMapper.selectList(null);

        // Step 2: 查询所有的作弊分析结果
        List<CheatAnalysisResult> cheatAnalysisResults = cheatAnalysisResultMapper.selectList(null);

        // Step 3: 创建一个 Map 用于存储 userId 到 overallRisk 的映射
        Map<Integer, Float> overallRiskMap = cheatAnalysisResults.stream()
                .collect(Collectors.toMap(
                        CheatAnalysisResult::getUserId,
                        CheatAnalysisResult::getOverallRisk,
                        Float::max  // 如果 key 冲突，保留较大的值
                ));

        // Step 4: 将 User 转换为 UserAdminDto，并填充 overallRisk
        List<UserAdminDto> userAdminDtoList = userList.stream()
                .map(user -> {
                    UserAdminDto dto = new UserAdminDto();
                    dto.setUserId(user.getId());
                    dto.setUsername(user.getUsername());
                    dto.setEmail(user.getEmail());
                    dto.setIsBanned(user.getIsBanned());
                    dto.setRegisterTime(user.getRegisterTime());
                    dto.setTotalUpload(user.getTotalUpload());
                    dto.setTotalDownload(user.getTotalDownload());
                    dto.setInviteCount(user.getInviteCount());
                    dto.setMagicValue(user.getMagicValue());
                    dto.setWorkCount(user.getWorkCount());
                    dto.setOverallRisk(overallRiskMap.getOrDefault(user.getId(), 0f)); // 注意这里的 getOrDefault
                    return dto;
                })
                .collect(Collectors.toList());

        // Step 5: 按 overallRisk 排序
        List<UserAdminDto> sortedList = userAdminDtoList.stream()
                .sorted(Comparator.comparing(UserAdminDto::getOverallRisk).reversed()) // 降序
                .collect(Collectors.toList());

        // Step 6: 分页
        int fromIndex = (page - 1) * size;

        // 检查 if fromIndex 超过了列表大小，返回空列表
        if (fromIndex >= sortedList.size()) {
            return Response.success(new ArrayList<>()); // 返回空列表
        }

        // 计算 toIndex
        int toIndex = Math.min(fromIndex + size, sortedList.size());
        List<UserAdminDto> pagedList = sortedList.subList(fromIndex, toIndex);

        return Response.success(pagedList);
    }

    public Response<CheatAnalysisResult> getAnalysisResult(String token, int userId) throws UserException {
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("验证码无效");
        }
        LambdaQueryWrapper<CheatAnalysisResult> cheatAnalysisResultWrapper = new LambdaQueryWrapper<>();
        cheatAnalysisResultWrapper.eq(CheatAnalysisResult::getUserId, userId);
        List<CheatAnalysisResult> results = cheatAnalysisResultMapper.selectList(cheatAnalysisResultWrapper);
        if (!results.isEmpty()) {
            // 根据需要返回第一条或做其他处理
            return Response.success(results.get(0));
        }
        return Response.success(null);
    }

    public Response<String> banned(String token, int userId) throws UserException {
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("验证码无效");
        }
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId, userId);
        User user = userMapper.selectOne(userWrapper);
        user.setIsBanned(true);
        userMapper.updateById(user);
        return Response.success("success");
    }

    public Response<String> unbanned(String token, int userId) throws UserException {
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("验证码无效");
        }
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId, userId);
        User user = userMapper.selectOne(userWrapper);

        user.setIsBanned(false);
        userMapper.updateById(user);
        return Response.success("success");
    }

    public Response<String> adminDeleteWork(String token, Integer workId) throws UserException {
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("验证码无效");
        }

        workMapper.deleteById(workId);
        return Response.success("success");

    }


    public Response<Work> setWorkOnSale(String token, Integer workId, boolean onSale, float netRate, float costRate) throws DBNotFoundExcepton, UserException, WorkException {
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("验证码无效");
        }

        Work work = workMapper.selectById(workId);
        if (work == null) {
            throw new DBNotFoundExcepton("作品不存在");
        }

        // 3. 创建更新条件和更新内容
        UpdateWrapper<Work> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", workId);

        // 4. 设置需要更新的字段
        Work updateWork = new Work();
        updateWork.setOnSale(onSale);
        updateWork.setNetRate(netRate);
        updateWork.setCostRate(costRate);

        // 5. 执行更新操作
        int rows = workMapper.update(updateWork, updateWrapper);
        if (rows <= 0) {
            throw new WorkException("更新失败，作品可能已被删除");
        }

        // 6. 查询更新后的作品信息
        Work updatedWork = workMapper.selectById(workId);
        return Response.success(updatedWork);
    }

    public Response<Page<Work>> getAllWorks(String token, int pageNum, int pageSize) throws UserException {
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("验证码无效");
        }
        Page<Work> page = new Page<>(pageNum, pageSize);
        Page<Work> resultPage = workMapper.selectPage(page, null);
        return Response.success(resultPage);

    }
}
